Cesium.Ion.defaultAccessToken = ''
    + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
    + '.eyJqdGkiOiJhYTNjMzFmMC0zMmFiLTRkO'
    + 'TMtODc1My0yMmUxNjdiZTNmOTgiLCJpZCI'
    + '6MjE0NjYxLCJpYXQiOjE3MTU1NjM4MzF9'
    + '.FrRllEey0E_5oELJJoqMGHXdO5C34QAfkNL6Taw8SFQ';

const viewer = new Cesium.Viewer('cesiumContainer', {
    // terrain: Cesium.Terrain.fromWorldTerrain(),
    animation: false,
    baseLayerPicker: true,
    fullscreenButton: false,
    vrButton: true,
    geocoder: false,
    homeButton: true,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    navigationHelpButton: false
});

// 设置初始视点高度和视角
viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(114.355, 30.49, 5000.0), // 视点高度1500米
    orientation: {
        heading: Cesium.Math.toRadians(0), // 正北方向
        pitch: Cesium.Math.toRadians(-45), // 俯角45度
        roll: 0.0
    }
});

// 添加拖放事件监听
const dropZone = document.getElementById('cesiumContainer');

dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragging');
});

dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragging');
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragging');

    const file = e.dataTransfer.files[0];
    if (!file || !file.name.endsWith('.glb')) return;

    const url = URL.createObjectURL(file);
    const rect = dropZone.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    const cartesian = viewer.scene.camera.pickEllipsoid(new Cesium.Cartesian2(x, y), viewer.scene.globe.ellipsoid);
    if (!cartesian) {
        alert('请在有效区域释放模型');
        return;
    }

    modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesian);

    Cesium.Model.fromGltfAsync({
        url: url,
        modelMatrix: modelMatrix,
        scale: 1.0,
        show: true
    }).then(function (model) {
        const primitive = viewer.scene.primitives.add(model);
        primitive.readyEvent.addEventListener(function () {

            viewer.camera.flyToBoundingSphere(primitive.boundingSphere, {
                duration: 1.0,
                offset: new Cesium.HeadingPitchRange(0, -Cesium.Math.PI_OVER_FOUR, 50)
            });
        })
    }).catch(function (error) {
        console.error('加载模型失败:', error);
    });
});

viewer.scene.globe.depthTestAgainstTerrain = true;
viewer.scene.skyBox.show = false;
viewer.scene.backgroundColor = Cesium.Color.WHITE;
